import constents from "../common/constents.js";

const httpConfig = constents.HTTP_CONFIG;
const defaultOptin = {
	method:httpConfig.method.get,
	timeout:httpConfig.timeout,
	contentType:httpConfig.contentType.JSON,
	params:undefined
}

class ajaxUlit{
	constructor(url,options=defaultOptin) {
	    this.url = httpConfig.baseUrl + url;
		this.options = {...defaultOptin,...options};
		this.method = this.options.method;
		this.xhr = null;
		this.init();
	}
	init(){
		this.xhr = new XMLHttpRequest();
		//监听
		this.listen();
		this.dealParams();
		// this.xhr.open(this.method,this.url);
		this.toSend();
	}
	listen(){
		this.xhr.onload = ()=>{
			if((this.xhr.status>=200&&this.xhr.status<300) || this.xhr.status == 304){
				this.options.success(this.xhr.response);
			}else{
				this.options.httpCodeErr(this.xhr.status);
			}
		};
		this.xhr.onerror = ()=>{
			this.options.error();
		};
		this.xhr.ontimeout = ()=>{
			this.options.timeout();
		};
		this.xhr.onabort = ()=>{
			this.options.abort();
		};
	}
	
	dealParams(){
		if(this.options.params){
			const params = this.options.params;
			// console.log(params);
			if(this.method == httpConfig.method.get){
				for(let key in params){
					this.url += `${this.url.includes('?')?'&':'?'}${key}=${params[key]}`
				}
			}
			if(this.method == httpConfig.method.post){
				this.options.params = JSON.stringify(params);
			}
		}
		this.xhr.open(this.method,this.url);
	}
	
	toSend(){
		if(this.method == httpConfig.method.post){
			this.xhr.setRequestHeader('content-type',httpConfig.contentType.JSON);
			this.xhr.send(this.options.params);
			return
		}
		this.xhr.send()
	}
	
	toAbort(){
		this.xhr.abort()
	}
}
export default ajaxUlit;